<?php


namespace app\api\controller;

use app\api\model\Account as AccountModel;

class Account
{
    //增
    public function add()
    {
        $no = input('get.no');
        $name = input('get.name');
        $gender = input('get.gender');
        $a = new AccountModel;
        //数据校验
        $data = $a->where('account_no', '=', $no)->find();
        //如果查询到的数据不为空
        if (!empty($data)) return '学号已存在~';
        $data = array();
        $data['account_no'] = $no;
        $data['account_name'] = $name;
        $data['account_gender'] = $gender;
        $data['add_time'] = time();
        return $a->insert($data);
    }

    //删
    public function del()
    {
        $id = input('get.id');
        $a = new AccountModel;
        if (strpos($id, ',') != false) {
            $id = substr($id, 0, strlen($id) - 1);
        }
        return $a->where('account_id', 'in', $id)->delete();
    }

    //查
    public function sel()
    {
        //查询方法有待完善
        $keyword=input('get.keyword');
        $condition =array();
        if (!empty($keyword)){
            $condition[]=['account_name|account_no','like','%'.$keyword.'%'];
        }

        $a = new AccountModel;
        $data = array();
        $data['code'] = 0;
        $data['msg'] = '';
        $data['count'] = 1000;
        $datas = $a->where($condition)->select();

        //{{a:1},{b:2}}
        foreach ($datas as $item) {
            $item['gender_name'] = $item['account_gender'] == 1 ? '男' : '女';
            $item['add_time_name'] = date('Y-m-d H:i:s', $item['add_time']);
        }

        $data['data'] = $datas;
        header('content-type:application/json');
        echo json_encode($data);
        die();
    }

    //改
    public function edit()
    {
        $id = input('get.id');
        $name = input('get.name');
        $gender = input('get.gender');
        $a = new AccountModel;
        $data = $a->where('account_id', '=', $id)->find();
        //如果查询到的数据不为空
        if (empty($data)) return '用户不存在~';
        $update = array();
        $update['account_name'] = $name;
        $update['account_gender'] = $gender;
        return $a->where('account_id', '=', $id)->update($update);
    }
}
